// 向下找到最近的指定组件
function findComponentDownward(context, componentName) {
  const childrens = context.$children
  let children = null

  if (childrens.length) {
    for (const child of childrens) {
      const name = child.$options._componentTag

      if (name === componentName) {
        children = child
        break
      } else {
        children = findComponentDownward(child, componentName)
        if (children) break
      }
    }
  }
  return children
}

// 向下找到所有指定的组件
function findComponentsDownward(context, componentName) {
  return context.$children.reduce((components, child) => {
    if (child.$options._componentTag === componentName) components.push(child)
    const foundChilds = findComponentsDownward(child, componentName)
    return components.concat(foundChilds)
  }, [])
}

// 自定义指令
export default {
  // el-tabs组件下有el-table组件时切换tab表格闪动及样式错乱问题解决
  update(el, binding, vNode) {
    const that = vNode.context
    that.$nextTick(() => {
      // 找到激活的pane组件
      const panes = findComponentsDownward(that, 'el-tab-pane') || []
      const activePanes = panes.filter((item) => item.active)
      // let pane = panes.find((item) => item.active);
      // 查找激活pane下的table
      if (!!activePanes && !!activePanes.length) {
        activePanes.forEach((pane) => {
          if (pane) {
            const table = findComponentDownward(pane, 'el-table')
            if (table) {
              table.doLayout()
            }
          }
        })
      }
    })
  }
}
